<%--
  @author Duminda Dharmakeerthi
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<script type="text/javascript ">
$(document).ready(function() {
    hideForm();
    $('.cancel').val($('#cancel').val());
});

$(document).ready(function() {
    $('#deed-tree').treegrid({
        title:$('#landGrantHistory').val(),
        nowrap: false,
        rownumbers: true,
        animate:true,
        collapsible:true,
        idField:'deed',
        treeField:'deed',
        frozenColumns:[
            [
                {title:$('#grantHistory').val(),field:'deed',width:140,
                    formatter:function(value) {
                        return '<span style="color:red">' + value + '</span>';
                    }
                }
            ]
        ],
        columns:[
            [
                {field:'name',title:$('#reference').val(),width:537},
                {field:'transfer',title:$('#transfer').val(),width:60}
            ]
        ]
    });
    loadAlienationTree();
});

function loadAlienationTree() {
    var grantId = $('#grantId').attr('value');
    var parent;
    $.getJSON('${pageContext.request.contextPath}/common/AlienationHistoryLookupService', {grantId:grantId}, function(list) {
        var AList = list.alienationList;
        var i = AList.length - 1;
        for (i; i > -1; i--) {
            // if (AList[i].immediateParent == null) {
            if (AList[i].immediateParentId == 0 || AList[i].immediateParentId == null) {
                parent = null;
            } else {
                // parent = $('#deed-tree').treegrid('find', getImmediateParentId(AList[i]));
                parent = $('#deed-tree').treegrid('find', AList[i].immediateParentId);
            }

            var id = AList[i].id;

            // if (checkExtent(AList[i])) {
            if (AList[i].landExtent == 0) {

                var data = [
                    {
                        deed: id,
                        name: AList[i].referenceNo,
                        transfer: ''
                    }
                ];
            } else {
                var data = [
                    {
                        deed: id,
                        name: AList[i].referenceNo,
                        transfer: '<input type="radio" name="mortgage-transfer" class="transfer" value="Transfer" onclick="transfer(' + id + ')"/>'
                    }
                ];
            }
            addAlienation(parent, data);
        }
    });
}
/*
 function getImmediateParentId(obj) {
 var p;
 $.each(obj, function(key, element) {
 if (key == "immediateParent") {
 p = element.id;
 }
 });
 return p;
 }

 function checkExtent(obj) {
 var extent;
 $.each(obj, function(key, element) {
 if (key == "land") {
 extent = element.landExtent;
 }
 });
 if (extent == 0) {
 return true;
 } else {
 return false;
 }
 }    */

function addAlienation(parent, data) {
    $('#deed-tree').treegrid('append', {
        parent: (parent ? parent.deed : null),
        data: data
    });
}

function transfer(parent) {
    $('#alienationId').val(parent);
    var url = '${"loadDeedInformation.do"}';
    $.get(url, $('#load-form').serialize(), function(data) {
        $('#transfer-details').html(data);
        $('#transfer-details').show();
        $('#complete-grant-tree').hide();
        $('.immediateParentId').val(parent);
        $('.updateMode').val('false');
        $('#completeGrantTree').hide();
        $('#addGrantDeed').show();
        $('.cancel').val($('#cancel').val());
        $('#tabs').tabs();
        disableUnEditableFields();
    });
}

function disableUnEditableFields() {
    var fields = new Array(
            'gnDivisionId',
            'localAuthorityId',
            'village',
            'nameOfTheLand'
            );
    enableFields(fields);
}

function hideForm() {
    $('#transfer-details').hide();
    $('#complete-grant-tree').show();
    unSelect();
}

function unSelect() {
    $('.transfer').attr('checked', false);
    $('#completeGrantTree').show();
    $('#addGrantDeed').hide();
}

function validateLandExtent() {
    var minExtent = (parseFloat($('#minExtent').val()) * 0.002529285264).toFixed(4);
    var maxExtent = (parseFloat($('#maxExtent').val()) * 0.002529285264).toFixed(4);
    var pls_enter_valid_no = $("#pls_enter_valid_no").val();
    $('#land-transfer').validate({
        rules:{
            hectareId:{
                number: true,
                range: [minExtent, maxExtent]
            }
        },
        message:{
            hectareId:{
                number: pls_enter_valid_no
            }
        },
        invalidHandler: function(form, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var invalidPanels = $(validator.invalidElements()).closest(".ui-tabs-panel", form);
                if (invalidPanels.size() > 0) {
                    $.each($.unique(invalidPanels.get()), function() {
                        $(this).siblings(".ui-tabs-nav")
                                .find("a[href='#" + this.id + "']").parent().not(".ui-tabs-selected")
                                .addClass("ui-state-error")
                                .show("pulsate", {times: 3});
                    });
                }
            }
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass(errorClass);
            $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
            var $panel = $(element).closest(".ui-tabs-panel", element.form);
            if ($panel.size() > 0) {
                if ($panel.find("." + errorClass + ":visible").size() == 0) {
                    $panel.siblings(".ui-tabs-nav").find("a[href='#" + $panel[0].id + "']")
                            .parent().removeClass("ui-state-error");
                }
            }
        }
    });
    $("#referenceNo").rules("add", {required:true, messages:{
        required:$('#pls_enter_reference_no').val()}
    });
    $("#mortgagePeriodInYears").rules("add", {digits:true, messages:{
        required:$('#pls_enter_valid_no').val()}
    });
    $("#mortgagePeriodInMonths").rules("add", {digits:true, messages:{
        required:$('#pls_enter_valid_no').val()}
    });
    $("#name").rules("add", {required:true, messages:{
        required:$('#this_field_required').val()}
    }); //TODO: name of the holder need to be renamed. Dont use term "name"
    $("#nic").rules("add", {NICNo:true, messages:{
        required:$('#pls_enter_valid_nic_no').val()}
    });
    $("#mobile").rules("add", {phoneNo:true, messages:{
        required:$('#pls_enter_valid_phone_no').val()}
    });
    $("#landPhone").rules("add", {phoneNo:true, messages:{
        required:$('#pls_enter_valid_phone_no').val()}
    });
    $("#email").rules("add", {email:true, messages:{
        required:$('#pls_enter_valid_email').val()}
    });
    $("#fax").rules("add", {phoneNo:true, messages:{
        required:$('#pls_enter_valid_fax_no').val()}
    });
    $("#dateOfBirth").rules("add", {ageValidate:true, messages:{
        required:$('#pls_enter_valid_age').val()}
    });
    ////////////////////
    $('#issueDate').rules("add", {
        isDateFormated:true,
        isFeatureDate:true,
        messages:{
            ageValidate:$('#pls_enter_valid_age').val()}
    });

    $('#folioDate').rules("add", {
        isDateFormated:true,
        isFeatureDate:true,
        messages:{
            ageValidate:$('#pls_enter_valid_age').val()}
    });
    $('#startedDate').rules("add", {
        isDateFormated:true,
        isFeatureDate:true,
        messages:{
            ageValidate:$('#pls_enter_valid_age').val()}
    });
}
</script>
<div id="init-land-grants-outer" class="form-outer">
    <table id="deed-tree" class="width-100">
        <%-- Deed tree will be here --%>
    </table>
    <s:if test="hasActionErrors()">
        <s:div id="message-box" class="message-box">
            <div class="action-err">
                <s:actionerror/>
            </div>
        </s:div>
    </s:if>
    <s:form method="POST" id="land-transfer" name="init-land-transfer-info">
        <fieldset id="transfer-details">

        </fieldset>
    </s:form>

    <form id="load-form">
        <s:hidden name="alienationId" id="alienationId"/>
    </form>
</div>
<div id="complete-grant-tree">
    <div class="form-button-div right-align">
        <s:form method="POST" name="complete-grant-tree">
            <s:hidden id="grantId" name="grantId"/>
            <s:submit id="completeGrantTree" action="completeLandInformationTree"
                      value="%{getText('save_and_complete.label')}"/>
        </s:form>
    </div>
</div>

<s:hidden id="landGrantHistory" value="%{getText('land_grant_history.label')}"/>
<s:hidden id="grantHistory" value="%{getText('grant_history.label')}"/>
<s:hidden id="reference" value="%{getText('reference.label')}"/>
<s:hidden id="transfer" value="%{getText('transfer.label')}"/>